import { useEffect, useState } from 'react'
import { Link } from 'react-router-dom'
import { useAuth } from '../../hooks/useAuth'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Card, CardHeader, CardContent } from '@/components/ui/card'

interface EmailVerifyData {
  email: string
  code: string
}


export default function Register() {
  const [email, setEmail] = useState('')
  const [password, setPassword] = useState('')
  const [name, setName] = useState('')
  const { register } = useAuth()
  const [error, setError] = useState('')
  const [verifyCode, setVerifyCode] = useState('')
  const [countdown, setCountdown] = useState(0)


  const validateForm = () => {
    if (password.length < 6) {
      setError('密码长度至少为6个字符')
      return false
    }
    if (!verifyCode) {
      setError('请输入验证码')
      return false
    }
    setError('')
    return true
  }

  const handleSendCode = async () => {
    if (!email) {
      setError('请输入邮箱')
      return
    }
    try {
      const response = await fetch('/api/auth/email-verify', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ email }),
      })
      if (!response.ok) {
        const data = await response.json()
        throw new Error(data.error || '发送验证码失败')
      }
      setCountdown(60)
      const timer = setInterval(() => {
        setCountdown((prev) => {
          if (prev <= 1) {
            clearInterval(timer)
            return 0
          }
          return prev - 1
        })
      }, 1000)
    } catch (error: any) {
      setError(error.message)
    }
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!validateForm()) return
    try {
      await register(email, password, name, verifyCode)
    } catch (error: any) {
      const message = error.message || '注册失败，请重试'
      setError(message)
    }
  }

  return (
    <div className="min-h-screen flex items-center justify-center bg-gray-50">
      <Card className="w-[400px]">
        <CardHeader>
          <h2 className="text-2xl font-bold text-center">注册账号</h2>
          <p className="text-center text-gray-500">创建您的运猫账号</p>
        </CardHeader>
        <CardContent>
          <form onSubmit={handleSubmit} className="space-y-4">
            {error && (
              <div className="text-red-500 text-sm text-center">{error}</div>
            )}
            <div>
              <Input
                type="text"
                placeholder="用户名"
                value={name}
                onChange={(e) => setName(e.target.value)}
                required
              />
            </div>
            <div>
              <Input
                type="email"
                placeholder="邮箱"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                required
              />
            </div>
            <div>
              <Input
                type="password"
                placeholder="密码（至少6个字符）"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                required
                minLength={6}
              />
            </div>
            <div className="flex gap-2">
              <Input
                type="text"
                placeholder="验证码"
                value={verifyCode}
                onChange={(e) => setVerifyCode(e.target.value)}
                required
              />
              <Button
                type="button"
                variant="outline"
                onClick={handleSendCode}
                disabled={countdown > 0}
              >
                {countdown > 0 ? `${countdown}秒后重试` : '获取验证码'}
              </Button>
            </div>
            <Button type="submit" className="w-full">
              注册
            </Button>
            <div className="text-center text-sm">
              <Link to="/login" className="text-blue-600 hover:text-blue-800">
                已有账号？立即登录
              </Link>
            </div>
          </form>
        </CardContent>
      </Card>
    </div>
  )
}